package com.app.megaprosoft.modyimcarcare;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import com.app.megaprosoft.DB.FFUser;
import com.app.megaprosoft.DB.SQLiteDBClass;
import com.app.megaprosoft.DB.ServicePOS;
import com.app.megaprosoft.DB.UserGroup;
import com.app.megaprosoft.general.DateTime;
import com.megaprosoft.modyimcarcare.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class Carcare_Main extends Activity {
	
	public static final int 	DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog 		mProgressDialog;
	
//	AlertDialog alert;
	private Button  bt_Service,
					bt_Reservice,
					bt_Updatedata,
					bt_Exit;
	
	private TextView tv_company,
					 tv_username,
					 tv_defname,
					 tv_service,
					 tv_check,
					 tv_all,
					 tv_date;
	
	private String   FFUserOID
					,UserName
					,DepCode
					,DepName
					,UserGroupOID
					,UserGroupName
					,PicPath
					,UserGroupCode="A"
					,ListService[][]
					,TabletCode;
	Toast mToast;
	
	private ListView Carcare_ServiceListView;
	
	//Intent
	private Intent  GetCar;
	
	private Boolean updateall = false;
	private Boolean update = true;
	
	private CarCare_Adapter_ListService carcare_listservice_adapter;
	
	UserGroup usergroup = new UserGroup();
	ServicePOS servicepos = new ServicePOS();
	FFUser ffuser = new FFUser();
	Carcare_SessionManagement session;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.a_carcare_activity_main);
		
		
		servicepos.setContext(getApplicationContext());
		ffuser.setContext(getApplicationContext());
		usergroup.setContext(getApplicationContext());
		
		tv_company 	= (TextView) findViewById(R.id.a_main_company);
		tv_username = (TextView) findViewById(R.id.a_main_username);
		tv_defname 	= (TextView) findViewById(R.id.a_main_depart);
		tv_date 	= (TextView) findViewById(R.id.a_main_date);
		
		tv_service 	= (TextView) findViewById(R.id.a_main_service);
		tv_check	= (TextView) findViewById(R.id.a_main_check); 
		tv_all 		= (TextView) findViewById(R.id.a_main_all);
		
		
		session = new Carcare_SessionManagement(getApplicationContext());
		session.checkLogin();
        HashMap<String, String> user = session.getUserDetails();

        FFUserOID = user.get(Carcare_SessionManagement.KEY_FFUserOID);
        UserName = user.get(Carcare_SessionManagement.KEY_UserName);
        DepCode = user.get(Carcare_SessionManagement.KEY_DepCode);
        DepName = user.get(Carcare_SessionManagement.KEY_DepName);
        UserGroupOID = user.get(Carcare_SessionManagement.KEY_UserGroupOID);
        UserGroupName = user.get(Carcare_SessionManagement.KEY_UserGroupName);
        UserGroupCode = user.get(Carcare_SessionManagement.KEY_UserGroupCode);
        PicPath = user.get(Carcare_SessionManagement.KEY_PicPath);
        TabletCode = user.get(Carcare_SessionManagement.KEY_TabletCode);
        
        tv_company.setText(UserGroupName);
		tv_username.setText(UserName);
		tv_defname.setText(DepName);
		tv_service.setText("-");
		tv_check.setText("-");
		tv_all.setText("-");
				
//////////////////////////////////////// Button /////////////////////////////		
		bt_Service = (Button) findViewById(R.id.carcare_service);
		bt_Service.setOnClickListener(buttonService);
		bt_Reservice = (Button) findViewById(R.id.carcare_reservice);
		bt_Reservice.setOnClickListener(buttonReService);
		bt_Updatedata = (Button) findViewById(R.id.carcare_checkservice);
		bt_Updatedata.setOnClickListener(buttonUpdatedata);
		bt_Exit = (Button) findViewById(R.id.carcare_exit);
		bt_Exit.setOnClickListener(buttonExit);
		
		Calendar mCalendar = Calendar.getInstance();
		
		tv_date.setText(getFormat().format(mCalendar.getTime()));

		GetCar = new Intent(Carcare_Main.this,CarCare_GetCar.class);
		
		Carcare_ServiceListView = (ListView) findViewById(R.id.carcare_service_listservice);
		
		Define_ListService();
		
	}
	public SimpleDateFormat getFormat(){
//	    return new SimpleDateFormat("MMM, yyyy");
		return new java.text.SimpleDateFormat("dd MMMM yyyy");
	}; 
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		servicepos.setContext(getApplicationContext());
		ffuser.setContext(getApplicationContext());
		usergroup.setContext(getApplicationContext());
		
//			try {
//				long check = servicepos.UpdatetoServer_POS();
//				if(check<0){
//					update =false;
////					Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
//				}else{
//					update =true;
//				}
//			} catch (Exception e) {
//				update =false;
//				
////				Toast.makeText(getApplicationContext(), "อัพเดทข้อมูลล้มเหลว", Toast.LENGTH_SHORT).show();
//			}	
			
		Define_ListService();
	}
	
	public void UpdateList(){
		try {
			long check = servicepos.UpdatetoServer_POSLIST();
			if(check<0){
//				Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
//			Toast.makeText(getApplicationContext(), "EE2", Toast.LENGTH_SHORT).show();
		}
		try {
			long check = servicepos.UpdatetoServer_POS();
			if(check<0){
				update =false;
//				Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
			}else{
				update =true;
			}
		} catch (Exception e) {
			update =false;
//			Toast.makeText(getApplicationContext(), "อัพเดทข้อมูลล้มเหลว", Toast.LENGTH_SHORT).show();
		}	
	}

	public void Define_ListService(){	
		carcare_listservice_adapter = new CarCare_Adapter_ListService(Carcare_Main.this, 
				R.layout.list_service, new ArrayList<CarCare_ListService>());
		Carcare_ServiceListView.setAdapter(carcare_listservice_adapter);
		int length = 0;
		try{
			ListService = servicepos.SelectAll_ServicePOS("0",UserGroupCode,"");
			length = ListService.length;
			tv_all.setText(String.valueOf(length));
		
		}catch(Exception e){
			
		}
//		final ArrayList< String> list = new ArrayList<String>();
		int Service=0;
		int check=0;
		for(int i=0;i<length;i++){
			try{
				String _idcar;
				if(ListService[i][2].equals("")){
					_idcar="ไม่ระบุ";
				}else{
					_idcar=ListService[i][2].toString();
				}
				carcare_listservice_adapter.insert(new CarCare_ListService( length-i,
																			ListService[i][1].toString(),
																			_idcar, 
																			ListService[i][5].toString(),
																			ListService[i][9].toString(),
																			ListService[i][8].toString(),
																			ListService[i][19].toString()),
																			0);
//				
				if(ListService[i][8].toString().equals("รอปล่อย")){
					check=check+1;
				}else{
					Service=Service+1;
				}
			}catch(Exception e){
				
			}
        }
		
		tv_check.setText(String.valueOf(check));
		tv_service.setText(String.valueOf(Service));
	
		
	}
	
	//----------------------Button Operation------------------------------//
    
	private OnClickListener buttonService = new OnClickListener() {
        public void onClick(View v) {
        	GetCar.putExtra("ServiceId", "");
        	GetCar.putExtra("MODE", "NEW");
			startActivity(GetCar);
        }
    };
    
    private OnClickListener buttonReService = new OnClickListener() {
        public void onClick(View v) {
//        	try {
//				long check = servicepos.UpdatetoServer_POSLIST();
//				if(check<0){
////					Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
//				}
//			} catch (Exception e) {
////				Toast.makeText(getApplicationContext(), "EE2", Toast.LENGTH_SHORT).show();
//			}
        	try {
    			long check = servicepos.DEFINE_ServicePOS(UserGroupCode);
    			if(check<0){
    				update =false;
    			}else{
    				update =true; 
    			}
    			Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
    		} catch (Exception e) {
    			update =false;
    			Toast.makeText(getApplicationContext(), "DEFINE ล้มเหลว", Toast.LENGTH_SHORT).show();
    		}	
        	Define_ListService();
        }
    };
    
    private OnClickListener buttonUpdatedata = new OnClickListener() {
        public void onClick(View v) {
//        	Company com = new Company();
//        	try{
////        		ResultSet rs = com.selectCompany();
////        		if(rs.next()){
////        			try {
////        				new Update().execute();
////    				} catch (Exception e) {
////    					Toast.makeText(getApplicationContext(), "อัพเดทข้อมูลล้มเหลว", Toast.LENGTH_SHORT).show();
////    				}
////        		}
//        	}catch(Exception e){
//        		Toast.makeText(getApplicationContext(), "อัพเดทข้อมูลล้มเหลว", Toast.LENGTH_SHORT).show();
//        	}finally{
//        		try {
////					com.closeConnecttion();
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//        	}
//        	try {
//				String Data[][] = servicepos.SelectAll_ServicePOS("", "dsfsdfds", "");
//				Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
//				Toast.makeText(getApplicationContext(), Data[0][0], Toast.LENGTH_SHORT).show();
//			} catch (Exception e1) {
//				// TODO Auto-generated catch block
//				Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show();
//			}
        	try {
    			long check = servicepos.UpdatetoServer_POS();
    			if(check<0){
    				update =false;
    				Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
    			}else{
    				update =true;
    			}
    		} catch (Exception e) {
    			update =false;
    			Toast.makeText(getApplicationContext(), "อัพเดท  Service ล้มเหลว", Toast.LENGTH_SHORT).show();
    		}	
        	
//        	
        	Define_ListService();
        	
        }
    };
    private OnClickListener buttonExit = new OnClickListener() {
        public void onClick(View v) {
        	onBackPressed();
        }
    };
     
    @Override
	public void onBackPressed() {
	  
	        new AlertDialog.Builder(this)
	        .setTitle("ออกจากระบบ")
	        .setIcon(R.drawable.erroralert)
	        .setMessage("ต้องการออกจากระบบ")
	                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

	                    public void onClick(DialogInterface arg0, int arg1) {
	                    	Intent newActivity = new Intent(Carcare_Main.this,Carcare_Login.class);
	            			startActivity(newActivity);
	            			session.logoutUser();
	                        finish();
	                    }
	                })
	                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() {

	                    public void onClick(DialogInterface arg0, int arg1) {
	                    	
	                    }
	                }).create().show();
	}
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle("อัพเดทข้อมูล");
            mProgressDialog.setMessage("ทำการอัพเดทข้อมูล.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
      
        default:
            return null;
        }
    }
    

    
 	//-----------AsyncTask-Loading----------------------------------//
    public class Update extends AsyncTask<String, Void, Void> {
        @SuppressWarnings("deprecation")
		protected void onPreExecute() {
        	super.onPreExecute();
        	updateall = false;
        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
//         	try {
//				long check = myDb.UpdateData();
//				if(check<0){
//					updateall = false;
//					Toast.makeText(getApplicationContext(), String.valueOf(check), Toast.LENGTH_SHORT).show();
//				}else{
//					updateall = true;
//				}
//			} catch (Exception e) {
//				updateall =false;
//				Toast.makeText(getApplicationContext(), "EE", Toast.LENGTH_SHORT).show();
//			}	
//    		try{
//    			myDb.DEFINE_ServicePOS(UserGroupCode+TabletCode);
//    		}catch(Exception e){
//    		}
        	SystemClock.sleep(5000);
        	updateall = true;
    		return null;
        }

        @SuppressWarnings("deprecation")
		protected void onPostExecute(Void unused) {
        	 dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
             removeDialog(DIALOG_DOWNLOAD_PROGRESS);
        	if(updateall){
//        		 alert.show();
                Define_ListService();
        		updateall = false;
        	}else{
        		
        	}
           
        }
        
    }
						
}
